package ms.server.api.crypto;

import ms.server.api.annotation.Encrypt;
import ms.server.api.bean.vo.ResultVO;
import ms.server.api.util.JacksonUtils;
import ms.server.api.util.RSAUtils;
import lombok.extern.slf4j.Slf4j;
import ms.server.api.annotation.Encrypt;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 返回结果数据处理类<br>
 * <p>
 * 对加了@Encrypt的方法的数据进行加密操作<br>
 * <p>
 *
 * @Author ybc
 * @Date 2021/7/6 18:09
 */
@Slf4j
@ControllerAdvice(basePackages = "ms.server.api.controller")
public class EncryptResponseAdvice implements ResponseBodyAdvice {

    @Value("${api.inner.private_key}")
    private String PRIVATE_KEY;

    @Override
    public boolean supports(MethodParameter methodParameter, Class converterType) {
        return methodParameter.getMethod().isAnnotationPresent(Encrypt.class);
    }

    @Override
    public Object beforeBodyWrite(Object body,
                                  MethodParameter methodParameter,
                                  MediaType selectedContentType,
                                  Class selectedConverterType,
                                  ServerHttpRequest request,
                                  ServerHttpResponse response) {
        try {
            log.info("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行加密");
            return JacksonUtils.objToJson(ResultVO.success(RSAUtils.encryptedDataOnJava(JacksonUtils.objToJson(body), PRIVATE_KEY)));
        } catch (Exception e) {
            log.error("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行加密出现异常：" + e.getMessage(), e);
            return body;
        }
    }
}
